<?php
if (!defined('ABSPATH')) { exit; }

// 检查权限
global $wp_spider_monitor;
$is_premium = false;
if (isset($wp_spider_monitor) && method_exists($wp_spider_monitor, 'is_premium_user')) {
    $is_premium = $wp_spider_monitor->is_premium_user();
}

// 获取当前标签页
$current_tab = sanitize_text_field($_GET['tab'] ?? 'spider-list');
$tabs = array(
    'spider-list' => '蜘蛛清单',
    'ip-segments' => '蜘蛛IP段',
    'fake-spiders' => '疑似伪蜘蛛',
    'block-rules' => '蜘蛛拦截'
);
?>

<div class="wrap">
    <h1>🕷️ 蜘蛛列表</h1>
    <p class="description">管理网站访问的蜘蛛爬虫，包括蜘蛛清单、IP段管理、伪蜘蛛识别和拦截规则</p>
    
    <!-- 标签页导航 -->
    <nav class="nav-tab-wrapper">
        <?php foreach ($tabs as $tab_key => $tab_name): ?>
            <?php 
            $is_premium_tab = in_array($tab_key, ['fake-spiders', 'block-rules']);
            $tab_class = 'nav-tab';
            if ($current_tab === $tab_key) {
                $tab_class .= ' nav-tab-active';
            }
            if ($is_premium_tab && !$is_premium) {
                $tab_class .= ' nav-tab-premium';
            }
            ?>
            <a href="#spider-<?php echo $tab_key; ?>" 
               class="<?php echo $tab_class; ?> spa-tab-link"
               data-tab="<?php echo $tab_key; ?>"
               <?php if ($is_premium_tab && !$is_premium): ?>
               onclick="showPremiumNotice('<?php echo $tab_name; ?>'); return false;"
               <?php endif; ?>>
                <?php echo $tab_name; ?>
                <?php if ($is_premium_tab && !$is_premium): ?>
                    <span class="premium-badge">🔒</span>
                <?php endif; ?>
            </a>
        <?php endforeach; ?>
    </nav>
    
    <div class="tab-content" id="spider-tab-content">
        <div class="tab-panel" id="spider-list-panel" style="display: <?php echo $current_tab === 'spider-list' ? 'block' : 'none'; ?>;">
            <!-- 蜘蛛清单 -->
            <div class="spider-list-section">
                <div class="section-header">
                    <h2>🕷️ 蜘蛛清单</h2>
                </div>
                
                <!-- 美化的筛选条件区域 -->
                <div class="filter-section">
                    <div class="filter-card">
                        <div class="filter-header">
                            <h3>🔍 筛选条件</h3>
                            <div class="filter-actions">
                                <button type="button" id="apply-filters" class="btn btn-primary">
                                    <span class="dashicons dashicons-search"></span>
                                    应用筛选
                                </button>
                                <button type="button" id="reset-filters" class="btn btn-secondary">
                                    <span class="dashicons dashicons-image-rotate"></span>
                                    重置
                                </button>
                            </div>
                        </div>
                        
                        <div class="filter-grid">
                            <div class="filter-group">
                                <label for="spider-list-period" class="filter-label">
                                    <span class="dashicons dashicons-calendar-alt"></span>
                                    时间范围
                                </label>
                                <select id="spider-list-period" class="filter-select">
                                    <option value="today">📅 今天</option>
                                    <option value="yesterday">📅 昨天</option>
                                    <option value="week" class="premium-option" data-premium="true">📅 最近7天 🔒</option>
                                    <option value="month" class="premium-option" data-premium="true">📅 最近30天 🔒</option>
                                </select>
                            </div>
                            
                            <div class="filter-group">
                                <label for="spider-type-filter" class="filter-label">
                                    <span class="dashicons dashicons-tag"></span>
                                    蜘蛛类型
                                </label>
                                <select id="spider-type-filter" class="filter-select">
                                    <option value="">🔍 所有类型</option>
                                    <option value="search_engine">🔍 搜索引擎</option>
                                    <option value="social_media">📱 社交媒体</option>
                                    <option value="seo_tools">⚙️ SEO工具</option>
                                    <option value="archive">📚 归档工具</option>
                                    <option value="unknown_bot">❓ 未知机器人</option>
                                </select>
                            </div>
                            
                            <div class="filter-group">
                                <label for="spider-search" class="filter-label">
                                    <span class="dashicons dashicons-search"></span>
                                    搜索蜘蛛
                                </label>
                                <input type="text" id="spider-search" class="filter-input" placeholder="输入蜘蛛名称..." />
                            </div>
                            
                            <div class="filter-group">
                                <label for="status-filter" class="filter-label">
                                    <span class="dashicons dashicons-admin-tools"></span>
                                    状态筛选
                                </label>
                                <select id="status-filter" class="filter-select">
                                    <option value="">🔄 所有状态</option>
                                    <option value="active">✅ 活跃</option>
                                    <option value="ignored">⏸️ 已忽略</option>
                                    <option value="blocked">🚫 已拦截</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="spider-list-container">
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select-all-spiders" /></th>
                                <th>蜘蛛名称</th>
                                <th>蜘蛛类型</th>
                                <th>最近来访</th>
                                <th>爬取URLs</th>
                                <th>占比</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="spider-list-body">
                            <tr><td colspan="8">加载中...</td></tr>
                        </tbody>
                    </table>
                    
                    <div class="bulk-actions">
                        <select id="bulk-action-select">
                            <option value="">批量操作</option>
                            <option value="ignore">忽略</option>
                            <option value="block">拦截</option>
                            <option value="unignore">取消忽略</option>
                            <option value="unblock">取消拦截</option>
                        </select>
                        <button id="apply-bulk-action" class="button">应用</button>
                    </div>
                </div>
        </div>
        </div>
        
        <div class="tab-panel" id="ip-segments-panel" style="display: <?php echo $current_tab === 'ip-segments' ? 'block' : 'none'; ?>;">
            <!-- 蜘蛛IP段 -->
            <div class="ip-segments-section">
                <div class="section-header">
                    <h2>蜘蛛IP段</h2>
                    <div class="section-controls">
                        <select id="ip-segments-period">
                            <option value="today">今天</option>
                            <option value="yesterday">昨天</option>
                            <option value="week">最近7天</option>
                            <option value="month">最近30天</option>
                        </select>
                        <input type="text" id="ip-search" placeholder="搜索IP段" />
                    </div>
                </div>
                
                <div class="ip-segments-container">
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select-all-ips" /></th>
                                <th>蜘蛛名称</th>
                                <th>IP段</th>
                                <th>访问次数</th>
                                <th>占比</th>
                                <th>最后访问</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="ip-segments-body">
                            <tr><td colspan="7">加载中...</td></tr>
                        </tbody>
                    </table>
                    
                    <div class="bulk-actions">
                        <select id="ip-bulk-action-select">
                            <option value="">批量操作</option>
                            <option value="block">拦截IP段</option>
                            <option value="unblock">取消拦截</option>
                        </select>
                        <button id="apply-ip-bulk-action" class="button">应用</button>
                    </div>
                </div>
        </div>
        </div>
        
        <div class="tab-panel" id="fake-spiders-panel" style="display: <?php echo $current_tab === 'fake-spiders' ? 'block' : 'none'; ?>;">
            <!-- 疑似伪蜘蛛 -->
            <div class="fake-spiders-section">
                <?php if (!$is_premium): ?>
                    <div class="premium-notice">
                        <div class="premium-restriction">
                            <span class="premium-icon">🔒</span>
                            <span class="premium-text">疑似伪蜘蛛功能需要激活PRO版本</span>
                            <a href="<?php echo isset($wp_spider_monitor) ? $wp_spider_monitor->get_license_page_url() : admin_url('admin.php?page=spider-license'); ?>" class="premium-link">立即激活</a>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="section-header">
                        <h2>疑似伪蜘蛛</h2>
                        <div class="section-controls">
                            <select id="fake-spiders-period">
                                <option value="today">今天</option>
                                <option value="yesterday">昨天</option>
                                <option value="week">最近7天</option>
                                <option value="month">最近30天</option>
                            </select>
                            <button id="refresh-fake-spiders" class="button">刷新检测</button>
                        </div>
                    </div>
                <?php endif; ?>
                
                <?php if ($is_premium): ?>
                <div class="fake-spiders-container">
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select-all-fake" /></th>
                                <th>蜘蛛名称</th>
                                <th>IP地址</th>
                                <th>User-Agent</th>
                                <th>可疑原因</th>
                                <th>访问次数</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="fake-spiders-body">
                            <tr><td colspan="7">加载中...</td></tr>
                        </tbody>
                    </table>
                    
                    <div class="bulk-actions">
                        <select id="fake-bulk-action-select">
                            <option value="">批量操作</option>
                            <option value="block">拦截</option>
                            <option value="ignore">忽略</option>
                        </select>
                        <button id="apply-fake-bulk-action" class="button">应用</button>
                    </div>
                </div>
                <?php endif; ?>
        </div>
        </div>
        
        <div class="tab-panel" id="block-rules-panel" style="display: <?php echo $current_tab === 'block-rules' ? 'block' : 'none'; ?>;">
            <!-- 蜘蛛拦截 -->
            <div class="block-rules-section">
                <div class="section-header">
                    <h2>蜘蛛拦截</h2>
                    <div class="section-controls">
                        <?php if ($is_premium): ?>
                            <button id="add-block-rule" class="button button-primary">添加拦截规则</button>
                            <select id="block-rules-filter">
                                <option value="">所有规则</option>
                                <option value="name">按名称</option>
                                <option value="ip">按IP</option>
                                <option value="range">按IP段</option>
                            </select>
                        <?php else: ?>
                            <div class="premium-restriction">
                                <span class="premium-icon">🔒</span>
                                <span class="premium-text">拦截规则管理需要激活许可证</span>
                                <a href="<?php echo isset($wp_spider_monitor) ? $wp_spider_monitor->get_license_page_url() : admin_url('admin.php?page=spider-license'); ?>" class="premium-link">立即激活</a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if ($is_premium): ?>
                <div class="block-rules-container">
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select-all-rules" /></th>
                                <th>拦截类型</th>
                                <th>蜘蛛名称/IP</th>
                                <th>创建时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="block-rules-body">
                            <tr><td colspan="6">加载中...</td></tr>
                        </tbody>
                    </table>
                <?php else: ?>
                <div class="block-rules-container">
                    <div class="premium-notice">
                        <div class="premium-restriction">
                            <span class="premium-icon">🔒</span>
                            <span class="premium-text">蜘蛛拦截功能需要激活PRO版本才能查看数据</span>
                            <a href="<?php echo isset($wp_spider_monitor) ? $wp_spider_monitor->get_license_page_url() : admin_url('admin.php?page=spider-license'); ?>" class="premium-link">立即激活</a>
                        </div>
                    </div>
                <?php endif; ?>
                    
                    <div class="bulk-actions">
                        <select id="rules-bulk-action-select">
                            <option value="">批量操作</option>
                            <option value="activate">激活</option>
                            <option value="deactivate">停用</option>
                            <option value="delete">删除</option>
                        </select>
                        <button id="apply-rules-bulk-action" class="button">应用</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加拦截规则模态框 -->
<div id="add-block-rule-modal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>添加拦截规则</h3>
            <span class="close">&times;</span>
        </div>
        <div class="modal-body">
            <form id="add-block-rule-form">
                <table class="form-table">
                    <tr>
                        <th scope="row">拦截类型</th>
                        <td>
                            <select name="block_type" id="block_type">
                                <option value="name">按蜘蛛名称</option>
                                <option value="ip">按IP地址</option>
                                <option value="range">按IP段</option>
                                <option value="name_ip">按名称+IP</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">蜘蛛名称</th>
                        <td>
                            <input type="text" name="spider_name" id="spider_name" class="regular-text" />
                            <p class="description">按名称拦截时必填</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">IP地址/IP段</th>
                        <td>
                            <input type="text" name="ip_address" id="ip_address" class="regular-text" />
                            <p class="description">按IP拦截时必填，IP段格式：192.168.1.0/24</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">备注</th>
                        <td>
                            <textarea name="description" id="description" rows="3" class="large-text"></textarea>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                    <button type="submit" class="button button-primary">添加规则</button>
                    <button type="button" class="button" onclick="closeModal()">取消</button>
                </p>
            </form>
        </div>
    </div>
</div>

<style>
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e1e5e9;
}

.section-header h2 {
    margin: 0;
    color: #333;
}

.section-controls {
    display: flex;
    gap: 10px;
    align-items: center;
}

.section-controls select,
.section-controls input {
    padding: 5px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.bulk-actions {
    margin-top: 15px;
    padding: 10px 0;
    border-top: 1px solid #e1e5e9;
    display: flex;
    gap: 10px;
    align-items: center;
}

.spider-status {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.status-normal { background: #e7f3ff; color: #0066cc; }
.status-ignored { background: #fff3cd; color: #856404; }
.status-blocked { background: #f8d7da; color: #721c24; }

.modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 0;
    border: 1px solid #888;
    border-radius: 8px;
    width: 80%;
    max-width: 600px;
}

.modal-header {
    padding: 20px;
    border-bottom: 1px solid #e1e5e9;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h3 {
    margin: 0;
    color: #333;
}

.close {
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.close:hover {
    color: #000;
}

.modal-body {
    padding: 20px;
}

.form-table th {
    width: 150px;
    padding: 10px 0;
    vertical-align: top;
}

.form-table td {
    padding: 10px 0;
}

.submit {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e1e5e9;
}
</style>

<script>
jQuery(document).ready(function($) {
    // 加载当前标签页数据
    loadCurrentTabData();
    
    // SPA标签页切换
    $('.spa-tab-link').on('click', function(e) {
        e.preventDefault();
        
        const $this = $(this);
        const tab = $this.data('tab');
        
        // 检查是否为付费功能
        if ($this.hasClass('nav-tab-premium')) {
            const tabName = $this.text().replace('🔒', '').trim();
            showPremiumNotice(tabName);
            return;
        }
        
        // 更新活动状态
        $('.spa-tab-link').removeClass('nav-tab-active');
        $this.addClass('nav-tab-active');
        
        // 切换标签页内容
        switchTab(tab);
    });
    
    // 切换标签页内容
    function switchTab(tab) {
        // 隐藏所有标签页
        $('.tab-panel').hide();
        
        // 显示选中的标签页
        const panelId = tab + '-panel';
        $('#' + panelId).show();
        
        // 加载对应标签页的数据
        switch(tab) {
            case 'spider-list':
                loadSpiderList();
                break;
            case 'ip-segments':
                loadIpSegments();
                break;
            case 'fake-spiders':
                loadFakeSpiders();
                break;
            case 'block-rules':
                loadBlockRules();
                break;
        }
    }
    
    // 蜘蛛清单相关事件
    $('#spider-list-period, #spider-type-filter').on('change', function() {
        // 简化验证：直接检查全局激活状态
        if ($(this).attr('id') === 'spider-list-period') {
            const period = $(this).val();
            if (period === 'week' || period === 'month') {
                if (!window.wpSpiderMonitor || !window.wpSpiderMonitor.subscription || !window.wpSpiderMonitor.subscription.is_premium) {
                    // 显示激活提示
                    const $selectedOption = $(this).find('option:selected');
                    if ($selectedOption.hasClass('premium-option')) {
                        alert('7天和30天数据查看需要激活PRO版本');
                        // 重置为今天
                        $(this).val('today');
                        return;
                    }
                }
            }
        }
        loadSpiderList();
    });
    
    $('#spider-search').on('input', function() {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(() => {
            loadSpiderList();
        }, 500);
    });
    
    // 批量操作
    $('#apply-bulk-action').on('click', function() {
        const action = $('#bulk-action-select').val();
        const selected = $('input[name="spider_ids[]"]:checked').map(function() {
            return $(this).val();
        }).get();
        
        if (!action || selected.length === 0) {
            alert('请选择操作和蜘蛛');
            return;
        }
        
        applyBulkAction('spider', action, selected);
    });
    
    // 添加拦截规则
    $('#add-block-rule').on('click', function() {
        $('#add-block-rule-modal').show();
    });
    
    $('.close').on('click', function() {
        closeModal();
    });
    
    $('#add-block-rule-form').on('submit', function(e) {
        e.preventDefault();
        addBlockRule();
    });
    
    function loadCurrentTabData() {
        // 获取当前活动的标签页
        const activeTab = $('.nav-tab-active').data('tab') || '<?php echo $current_tab; ?>';
        switchTab(activeTab);
    }
    
    // 显示PRO版本提示
    function showPremiumNotice(tabName) {
        alert(tabName + '功能需要激活PRO版本才能使用。\n\n请前往许可证页面激活PRO版本。');
        window.location.href = '<?php echo admin_url('admin.php?page=spider-license'); ?>';
    }
    
    // 筛选功能
    $(document).ready(function() {
        // 应用筛选
        $('#apply-filters').click(function() {
            loadSpiderList();
        });
        
        // 重置筛选
        $('#reset-filters').click(function() {
            $('#spider-list-period').val('today');
            $('#spider-type-filter').val('');
            $('#spider-search').val('');
            $('#status-filter').val('');
            loadSpiderList();
        });
        
        // 回车键应用筛选
        $('#spider-search').keypress(function(e) {
            if (e.which === 13) {
                loadSpiderList();
            }
        });
    });
    
    function loadSpiderList() {
        $('#spider-list-body').html('<tr><td colspan="8">加载中...</td></tr>');
        
        $.post(ajaxurl, {
            action: 'spider_get_spider_list',
            period: $('#spider-list-period').val(),
            search: $('#spider-search').val(),
            type: $('#spider-type-filter').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                let html = '';
                
                // 显示PRO版本提示
                if (!response.data.is_premium && response.data.premium_message) {
                    html += '<tr><td colspan="8" class="premium-notice">';
                    html += '<div class="premium-restriction">';
                    html += '<span class="premium-icon">🔒</span>';
                    html += '<span class="premium-text">' + response.data.premium_message + '</span>';
                    html += '<a href="' + response.data.upgrade_url + '" class="premium-link">立即激活</a>';
                    html += '</div>';
                    html += '</td></tr>';
                }
                
                if (response.data.spiders && response.data.spiders.length > 0) {
                    response.data.spiders.forEach(function(spider) {
                        html += '<tr>';
                        html += '<td><input type="checkbox" name="spider_ids[]" value="' + spider.id + '" /></td>';
                        html += '<td>' + spider.spider_name + '</td>';
                        html += '<td>' + spider.bot_type + '</td>';
                        html += '<td>' + spider.last_visit + '</td>';
                        html += '<td>' + spider.url_count + '</td>';
                        html += '<td>' + spider.percentage + '%</td>';
                        html += '<td><span class="spider-status status-' + spider.status + '">' + spider.status_text + '</span></td>';
                        html += '<td>';
                        if (response.data.is_premium) {
                            var ignoreTarget = (spider.status === 'ignored') ? 'normal' : 'ignored';
                            var ignoreText = (spider.status === 'ignored') ? '取消忽略' : '忽略';
                            var blockTarget = (spider.status === 'blocked') ? 'normal' : 'blocked';
                            var blockText = (spider.status === 'blocked') ? '取消拦截' : '拦截';
                            html += '<button class="button button-small" onclick="toggleSpiderStatus(\'' + spider.id + '\', \'' + ignoreTarget + '\')">' + ignoreText + '</button> ';
                            html += '<button class="button button-small" onclick="toggleSpiderStatus(\'' + spider.id + '\', \'' + blockTarget + '\')">' + blockText + '</button>';
                        } else {
                            html += '<span class="premium-disabled">需要PRO版本</span>';
                        }
                        html += '</td>';
                        html += '</tr>';
                    });
                } else {
                    html += '<tr><td colspan="8">暂无数据</td></tr>';
                }
                $('#spider-list-body').html(html);
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '访问令牌无效或已过期';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                var html = '';
                html += '<tr><td colspan="8" class="premium-notice">';
                html += '<div class="premium-restriction">';
                html += '<span class="premium-icon">🔒</span>';
                html += '<span class="premium-text">' + msg + '</span>';
                html += '<a href="' + url + '" class="premium-link">立即激活</a>';
                html += '</div>';
                html += '</td></tr>';
                $('#spider-list-body').html(html);
            }
        }).fail(function(xhr, status, error) {
            $('#spider-list-body').html('<tr><td colspan="8">请求失败: ' + error + '</td></tr>');
        });
    }
    
    function loadIpSegments() {
        $('#ip-segments-body').html('<tr><td colspan="7">加载中...</td></tr>');
        
        $.post(ajaxurl, {
            action: 'spider_get_ip_segments',
            period: $('#ip-segments-period').val(),
            search: $('#ip-search').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                let html = '';
                
                if (response.data.segments && response.data.segments.length > 0) {
                    response.data.segments.forEach(function(segment) {
                        html += '<tr>';
                        html += '<td><input type="checkbox" name="ip_ids[]" value="' + segment.id + '" /></td>';
                        html += '<td>' + segment.spider_name + '</td>';
                        html += '<td>' + segment.ip_segment + '</td>';
                        html += '<td>' + segment.visit_count + '</td>';
                        html += '<td>' + segment.percentage + '%</td>';
                        html += '<td>' + segment.last_visit + '</td>';
                        html += '<td>';
                        html += '<button class="button button-small" onclick="blockIpSegment(\'' + segment.id + '\')">拦截</button>';
                        html += '</td>';
                        html += '</tr>';
                    });
                } else {
                    html += '<tr><td colspan="7">暂无数据</td></tr>';
                }
                $('#ip-segments-body').html(html);
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '访问令牌无效或已过期';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                var html = '';
                html += '<tr><td colspan="7" class="premium-notice">';
                html += '<div class="premium-restriction">';
                html += '<span class="premium-icon">🔒</span>';
                html += '<span class="premium-text">' + msg + '</span>';
                html += '<a href="' + url + '" class="premium-link">立即激活</a>';
                html += '</div>';
                html += '</td></tr>';
                $('#ip-segments-body').html(html);
            }
        }).fail(function(xhr, status, error) {
            $('#ip-segments-body').html('<tr><td colspan="7">请求失败: ' + error + '</td></tr>');
        });
    }
    
    function loadFakeSpiders() {
        $('#fake-spiders-body').html('<tr><td colspan="7">加载中...</td></tr>');
        
        $.post(ajaxurl, {
            action: 'spider_get_fake_spiders',
            period: $('#fake-spiders-period').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                let html = '';
                
                // 显示PRO版本提示
                if (!response.data.is_premium && response.data.premium_message) {
                    html += '<tr><td colspan="7" class="premium-notice">';
                    html += '<div class="premium-restriction">';
                    html += '<span class="premium-icon">🔒</span>';
                    html += '<span class="premium-text">' + response.data.premium_message + '</span>';
                    html += '<a href="' + response.data.upgrade_url + '" class="premium-link">立即激活</a>';
                    html += '</div>';
                    html += '</td></tr>';
                }
                
                if (response.data.fake_spiders && response.data.fake_spiders.length > 0) {
                    response.data.fake_spiders.forEach(function(fake) {
                        html += '<tr>';
                        html += '<td><input type="checkbox" name="fake_ids[]" value="' + fake.id + '" /></td>';
                        html += '<td>' + fake.spider_name + '</td>';
                        html += '<td>' + fake.ip_address + '</td>';
                        html += '<td title="' + fake.user_agent + '">' + fake.user_agent.substring(0, 50) + '...</td>';
                        html += '<td>' + fake.fake_reason + '</td>';
                        html += '<td>' + fake.visit_count + '</td>';
                        html += '<td>';
                        if (response.data.is_premium) {
                            html += '<button class="button button-small" onclick="blockFakeSpider(\'' + fake.id + '\')">拦截</button>';
                        } else {
                            html += '<span class="premium-disabled">需要PRO版本</span>';
                        }
                        html += '</td>';
                        html += '</tr>';
                    });
                } else {
                    html += '<tr><td colspan="7">暂无数据</td></tr>';
                }
                $('#fake-spiders-body').html(html);
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '访问令牌无效或已过期';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                var html = '';
                html += '<tr><td colspan="7" class="premium-notice">';
                html += '<div class="premium-restriction">';
                html += '<span class="premium-icon">🔒</span>';
                html += '<span class="premium-text">' + msg + '</span>';
                html += '<a href="' + url + '" class="premium-link">立即激活</a>';
                html += '</div>';
                html += '</td></tr>';
                $('#fake-spiders-body').html(html);
            }
        }).fail(function(xhr, status, error) {
            $('#fake-spiders-body').html('<tr><td colspan="7">请求失败: ' + error + '</td></tr>');
        });
    }
    
    function loadBlockRules() {
        $('#block-rules-body').html('<tr><td colspan="6">加载中...</td></tr>');
        
        $.post(ajaxurl, {
            action: 'spider_get_block_rules',
            filter: $('#block-rules-filter').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                let html = '';
                
                // 显示PRO版本提示
                if (!response.data.is_premium && response.data.premium_message) {
                    html += '<tr><td colspan="6" class="premium-notice">';
                    html += '<div class="premium-restriction">';
                    html += '<span class="premium-icon">🔒</span>';
                    html += '<span class="premium-text">' + response.data.premium_message + '</span>';
                    html += '<a href="' + response.data.upgrade_url + '" class="premium-link">立即激活</a>';
                    html += '</div>';
                    html += '</td></tr>';
                }
                
                if (response.data.rules && response.data.rules.length > 0) {
                    response.data.rules.forEach(function(rule) {
                        html += '<tr>';
                        html += '<td><input type="checkbox" name="rule_ids[]" value="' + rule.id + '" /></td>';
                        html += '<td>' + rule.block_type + '</td>';
                        html += '<td>' + (rule.spider_name || rule.ip_address || rule.ip_range) + '</td>';
                        html += '<td>' + rule.created_at + '</td>';
                        html += '<td>' + (rule.is_active ? '激活' : '停用') + '</td>';
                        html += '<td>';
                        if (response.data.is_premium) {
                            html += '<button class="button button-small" onclick="toggleRuleStatus(' + rule.id + ', ' + rule.is_active + ')">';
                            html += rule.is_active ? '停用' : '激活';
                            html += '</button>';
                            html += '<button class="button button-small" onclick="deleteRule(' + rule.id + ')">删除</button>';
                        } else {
                            html += '<span class="premium-disabled">需要PRO版本</span>';
                        }
                        html += '</td>';
                        html += '</tr>';
                    });
                } else {
                    html += '<tr><td colspan="6">暂无数据</td></tr>';
                }
                $('#block-rules-body').html(html);
            } else {
                var msg = (response.data && response.data.message) ? response.data.message : '访问令牌无效或已过期';
                var url = (response.data && response.data.upgrade_url) ? response.data.upgrade_url : '<?php echo admin_url('admin.php?page=spider-license'); ?>';
                var html = '';
                html += '<tr><td colspan="6" class="premium-notice">';
                html += '<div class="premium-restriction">';
                html += '<span class="premium-icon">🔒</span>';
                html += '<span class="premium-text">' + msg + '</span>';
                html += '<a href="' + url + '" class="premium-link">立即激活</a>';
                html += '</div>';
                html += '</td></tr>';
                $('#block-rules-body').html(html);
            }
        }).fail(function(xhr, status, error) {
            $('#block-rules-body').html('<tr><td colspan="6">请求失败: ' + error + '</td></tr>');
        });
    }
    
    function addBlockRule() {
        const formData = {
            action: 'spider_add_block_rule',
            block_type: $('#block_type').val(),
            spider_name: $('#spider_name').val(),
            ip_address: $('#ip_address').val(),
            description: $('#description').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        };
        
        $.post(ajaxurl, formData, function(response) {
            if (response.success) {
                alert('拦截规则添加成功');
                closeModal();
                loadBlockRules();
            } else {
                alert('添加失败：' + response.data);
            }
        });
    }
    
    function closeModal() {
        $('#add-block-rule-modal').hide();
        $('#add-block-rule-form')[0].reset();
    }
    
    function applyBulkAction(type, action, ids) {
        $.post(ajaxurl, {
            action: 'spider_bulk_action',
            type: type,
            action_name: action,
            ids: ids,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                alert('批量操作成功');
                loadCurrentTabData();
            } else {
                alert('操作失败：' + response.data);
            }
        });
    }
    // 暴露刷新函数到全局，供外部回调使用
    window.loadCurrentTabData = loadCurrentTabData;
    window.loadSpiderList = loadSpiderList;
});

// 全局函数
function toggleSpiderStatus(id, targetStatus) {
    const newStatus = targetStatus;
    jQuery.post(ajaxurl, {
        action: 'spider_toggle_status',
        id: id,
        status: newStatus,
        nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
    }, function(response) {
        if (response.success) {
            // 无需整页刷新：仅重新加载当前标签页数据
            if (typeof loadCurrentTabData === 'function') {
                loadCurrentTabData();
            } else if (typeof loadSpiderList === 'function') {
                loadSpiderList();
            }
        } else {
            alert('更新失败：' + response.data);
        }
    });
}

function blockIpSegment(id) {
    if (confirm('确定要拦截这个IP段吗？')) {
        jQuery.post(ajaxurl, {
            action: 'spider_block_ip_segment',
            id: id,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                alert('IP段拦截成功');
                location.reload();
            } else {
                alert('拦截失败：' + response.data);
            }
        });
    }
}

function blockFakeSpider(id) {
    if (confirm('确定要拦截这个伪蜘蛛吗？')) {
        jQuery.post(ajaxurl, {
            action: 'spider_block_fake_spider',
            id: id,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                alert('伪蜘蛛拦截成功');
                location.reload();
            } else {
                alert('拦截失败：' + response.data);
            }
        });
    }
}

function toggleRuleStatus(id, isActive) {
    const newStatus = isActive ? 0 : 1;
    jQuery.post(ajaxurl, {
        action: 'spider_toggle_rule_status',
        id: id,
        is_active: newStatus,
        nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
    }, function(response) {
        if (response.success) {
            alert('规则状态更新成功');
            location.reload();
        } else {
            alert('更新失败：' + response.data);
        }
    });
}

function deleteRule(id) {
    if (confirm('确定要删除这个拦截规则吗？')) {
        jQuery.post(ajaxurl, {
            action: 'spider_delete_rule',
            id: id,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                alert('规则删除成功');
                location.reload();
            } else {
                alert('删除失败：' + response.data);
            }
        });
    }
}
</script>

<style>
/* 付费功能限制样式 */
.premium-restriction {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 15px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 6px;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
}

.premium-restriction:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.premium-icon {
    font-size: 16px;
    animation: pulse 2s infinite;
}

.premium-text {
    flex: 1;
    font-weight: 500;
}

.premium-link {
    background: rgba(255, 255, 255, 0.2);
    color: white;
    padding: 6px 12px;
    border-radius: 4px;
    text-decoration: none;
    font-weight: 600;
    transition: all 0.3s ease;
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.premium-link:hover {
    background: rgba(255, 255, 255, 0.3);
    color: white;
    text-decoration: none;
    transform: scale(1.05);
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* 禁用状态样式 */
.premium-disabled {
    opacity: 0.6;
    pointer-events: none;
    position: relative;
    color: #999;
    font-size: 12px;
    font-style: italic;
}

.premium-disabled::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    z-index: 1;
}

/* PRO版本提示样式 */
.premium-notice {
    background: #f8f9fa;
    border-left: 4px solid #007cba;
}

.premium-notice .premium-restriction {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 15px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 6px;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
}

.premium-notice .premium-restriction:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.premium-notice .premium-icon {
    font-size: 16px;
    animation: pulse 2s infinite;
}

.premium-notice .premium-text {
    flex: 1;
    font-weight: 500;
}

.premium-notice .premium-link {
    background: rgba(255, 255, 255, 0.2);
    color: white;
    padding: 6px 12px;
    border-radius: 4px;
    text-decoration: none;
    font-weight: 600;
    transition: all 0.3s ease;
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.premium-notice .premium-link:hover {
    background: rgba(255, 255, 255, 0.3);
    color: white;
    text-decoration: none;
    transform: scale(1.05);
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* PRO版本标签页样式 */
.nav-tab-premium {
    position: relative;
    opacity: 0.7;
}

.nav-tab-premium:hover {
    opacity: 1;
}

.premium-badge {
    margin-left: 5px;
    font-size: 12px;
    animation: pulse 2s infinite;
}

/* 美化的筛选条件样式 */
.filter-section {
    margin-bottom: 25px;
}

.filter-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
}

.filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 2px solid rgba(255, 255, 255, 0.2);
}

.filter-header h3 {
    color: white;
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-actions {
    display: flex;
    gap: 12px;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.btn-primary {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(79, 172, 254, 0.4);
}

.btn-secondary {
    background: rgba(255, 255, 255, 0.2);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.btn-secondary:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-2px);
}

.filter-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
    width: 100%;
}

.filter-label {
    display: flex;
    align-items: center;
    gap: 8px;
    color: white;
    font-weight: 500;
    font-size: 14px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.filter-label .dashicons {
    font-size: 16px;
    opacity: 0.9;
}

.filter-select,
.filter-input {
    padding: 12px 16px;
    border: 2px solid rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.95);
    color: #333;
    font-size: 14px;
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    min-height: 44px;
    flex: 1;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
}

.filter-select:focus,
.filter-input:focus {
    outline: none;
    border-color: #4facfe;
    box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.2);
    transform: translateY(-1px);
}

.filter-select:hover,
.filter-input:hover {
    border-color: rgba(255, 255, 255, 0.4);
    transform: translateY(-1px);
}

.filter-input::placeholder {
    color: #999;
    font-style: italic;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .filter-grid {
        grid-template-columns: repeat(3, 1fr);
        gap: 18px;
    }
}

@media (max-width: 960px) {
    .filter-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
    }
}

@media (max-width: 600px) {
    .filter-grid {
        grid-template-columns: 1fr;
        gap: 15px;
    }
    
    .filter-header {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
    }
    
    .filter-actions {
        justify-content: center;
    }
    
    .btn {
        flex: 1;
        justify-content: center;
    }
}

/* 动画效果 */
@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.filter-card {
    animation: slideInUp 0.6s ease-out;
}

.filter-group {
    animation: slideInUp 0.6s ease-out;
    animation-fill-mode: both;
}

.filter-group:nth-child(1) { animation-delay: 0.1s; }
.filter-group:nth-child(2) { animation-delay: 0.2s; }
.filter-group:nth-child(3) { animation-delay: 0.3s; }
.filter-group:nth-child(4) { animation-delay: 0.4s; }

/* SPA标签页样式 */
.spa-tab-link {
    cursor: pointer;
    transition: all 0.3s ease;
}

.spa-tab-link:hover {
    background-color: #f1f1f1;
}

.tab-panel {
    display: none;
    animation: fadeIn 0.3s ease-in-out;
}

.tab-panel.active {
    display: block;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}
</style>
